<?php
// 设置允许的来源
// header("Access-Control-Allow-Origin: http://localhost:9528");
header("Access-Control-Allow-Origin: http://1.13.198.191:8081");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

// 处理预检请求（OPTIONS）
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// 连接数据库
require_once "./conn.php";
// require_once "./usersession.php";

if ($conn->connect_error) {
    die(json_encode(["Code" => 500, "Msg" => "连接错误: " . $conn->connect_error]));
}

// 获取前端传递的 JSON 数据
$data = json_decode(file_get_contents("php://input"), true);

// 提取中控账号和配置名
$zhongkong_account = $data['yunduan_zhanghao'];
$config_name =  $data['peizhiming'];

// 检查是否成功提取中控账号和配置名
if (empty($zhongkong_account) || empty($config_name)) {
    echo json_encode(["Code" => 400, "Msg" => "缺少中控账号或配置名", "Data" => ""]);
    exit;
}

// 查询配置是否存在
$sql_check = "SELECT * FROM configurations WHERE zhongkong_name = '$zhongkong_account' AND name = '$config_name'";
$result = $conn->query($sql_check);

$modifyTime = date("Y-m-d H:i:s");
$settings = $conn->real_escape_string(json_encode($data));

if ($result->num_rows > 0) {
    // 配置存在，执行更新操作
    $sql_update = "UPDATE configurations SET settings = '$settings', modifyTime = '$modifyTime' WHERE zhongkong_name = '$zhongkong_account' AND name = '$config_name'";
    if ($conn->query($sql_update) === TRUE) {
        echo json_encode(["Code" => 200, "Msg" => "配置修改成功", "Data" => ""]);
    } else {
        echo json_encode(["Code" => 500, "Msg" => "修改错误: " . $conn->error, "Data" => ""]);
    }
} else {
    // 配置不存在，执行新增操作
    $addTime = date("Y-m-d H:i:s");

    $sql_insert = "INSERT INTO configurations (zhongkong_name, name, settings,addTime, modifyTime) VALUES ('$zhongkong_account', '$config_name', '$settings','$addTime', '$modifyTime')";
    if ($conn->query($sql_insert) === TRUE) {
        echo json_encode(["Code" => 200, "Msg" => "配置新增成功", "Data" => ""]);
    } else {
        echo json_encode(["Code" => 500, "Msg" => "新增错误: " . $conn->error, "Data" => ""]);
    }
}

$conn->close();
